package com.kexin.jbsg.guansdk;

import java.util.Random;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kexin.jbsg.AbstractUnityActivity;
import com.kexin.jbsg.guansdk.interfaces.GuanSDK;
import com.kexin.jbsg.guansdk.model.KomLoginResponseData;
import com.kexin.jbsg.guansdk.utils.Util;

public class RegisterActivity extends Activity implements OnClickListener{
	public final static int VISIBLE_GONE=8;
	public final static int VISIBLE_VISIBLE=0;

	EditText et_userAccount;
	EditText et_pwd;
	Button btn_register;
	Button btn_random;
	Button btn_back;
	
	TextView tv_msg_userAccount;
	TextView tv_msg_password;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		Intent intent = this.getIntent();
		this.setResult(KomSDKInfo.RESULT_CODE_REGISTER, intent);
		
		et_userAccount = (EditText) findViewById(R.id.register_userAccount);
		et_pwd = (EditText) findViewById(R.id.register_password);
		tv_msg_userAccount = (TextView) findViewById(R.id.register_msg_userAccount);
		tv_msg_password = (TextView) findViewById(R.id.register_msg_password);
		btn_register = (Button) findViewById(R.id.register_btn_register);
		btn_register.setOnClickListener(this);
		btn_random = (Button) findViewById(R.id.register_btn_random);
		btn_random.setOnClickListener(this);
		btn_back = (Button) findViewById(R.id.register_back);
		btn_back.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.register_btn_register) {
			//创建帐号
			boolean registerResult = simpleValidate();
			if(registerResult){
				final Handler registerHandler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						String message = msg.getData().getString("errorMessage");
						if(!message.equals("")){
							Toast.makeText(RegisterActivity.this, message,Toast.LENGTH_SHORT).show();
						}
							
					}
				};
				
				//发送到服务器进行校验
				//需要异步
				final ProgressDialog dialog = Util.showProgressDialog(this,"正在创建帐号");
				new Thread(){
					public void run() {
						StringBuilder params = new StringBuilder();
						params.append("?userAccount="+getUserAccount());
						params.append("&password="+getPassword());
						params.append("&channel="+GuanSDK.channel);
						params.append("&actionCode="+KomSDKInfo.ACTION_CODE_REGISTER);
						String result  = Util.getWebCon((GuanSDK.debug?AbstractUnityActivity.LOGINURL_DEBUG:AbstractUnityActivity.LOGINURL)+params.toString());
						Object odata = Util.decodeJson(result, KomLoginResponseData.class);
						dialog.dismiss();
						if(odata!=null){
							KomLoginResponseData kdata = (KomLoginResponseData) odata;
							if(kdata.getCode()==1){
								//返回创建帐号结果
								getIntent().putExtra("registerResult", true);
								getIntent().putExtra("userAccount", getUserAccount());
								getIntent().putExtra("password", getPassword());
								getIntent().putExtra("sign", kdata.getSign());
								getIntent().putExtra("time", kdata.getTime());
								RegisterActivity.this.finish();
							}else{
								Message msg = new Message();
								Bundle errorData = new Bundle();
								errorData.putString("errorMessage", kdata.getErrorDesc());
								msg.setData(errorData);
								registerHandler.sendMessage(msg);
							}
						}else{
							Message msg = new Message();
							Bundle errorData = new Bundle();
							errorData.putString("errorMessage", "连接服务器失败请重试");
							msg.setData(errorData);
							registerHandler.sendMessage(msg);
						}
					};
				}.start();
			}
		} else if (id == R.id.register_back) {
			//返回登录
			this.finish();
		} else if (id == R.id.register_btn_random) {
			randomUserInfo();
		} else {
		}
	}
	
	/**
	 * 随机帐号密码
	 */
	public void randomUserInfo(){
		StringBuilder userAccount = new StringBuilder();
		Random typeRandom = new Random();
		for(int i=0;i<6;i++){
			char randomResult = '1';
			int type = typeRandom.nextInt(2);
			switch (type) {
			case 0:
				randomResult = randomNum();
				break;
			case 1:
				randomResult = randomLw();
				break;
			case 2:
				randomResult = randomSw();
				break;
			default:
				break;
			}
			userAccount.append(randomResult);
		}
		
		et_userAccount.setText(userAccount);
		
		StringBuilder password = new StringBuilder();
		for(int i=0;i<6;i++){
			char randomResult = '1';
			int type = typeRandom.nextInt(2);
			switch (type) {
			case 0:
				randomResult = randomNum();
				break;
			case 1:
				randomResult = randomLw();
				break;
			case 2:
				randomResult = randomSw();
				break;
			default:
				break;
			}
			password.append(randomResult);
		}
		et_pwd.setText(password);
	}
	
	/**
	 * 随机数字
	 * @return
	 */
	public char randomNum(){
		Random random = new Random();
		int value = random.nextInt(57-48)+48;
		char result = (char)value;
		return result;
	}
	
	/**
	 * 随机小写字母
	 * @return
	 */
	public char randomSw(){
		Random random = new Random();
		int value = random.nextInt(90-65)+65;
		char result = (char)value;
		return result;
	}
	
	/**
	 * 随机大写字母
	 * @return
	 */
	public char randomLw(){
		Random random = new Random();
		int value = random.nextInt(122-97)+97;
		char result = (char)value;
		return result;
	}
	
	
	
	/**
	 * 简单校验  
	 * @return
	 */
	public boolean simpleValidate(){
		boolean result = false;
		String userAccountErrorMsg = "";
		String passwordErrorMsg = "";
		String userAccount = getUserAccount();
		String password = getPassword();
		
		//帐号
		if(userAccount==null){
			userAccountErrorMsg="帐号不能为空";
		}else{
			if(userAccount.length()<6&&userAccount.length()<11){
				userAccountErrorMsg="帐号长度不能小于6位";
			}else{
				if(!validateUserAccount(userAccount)){
					userAccountErrorMsg="帐号只能包含数字和字母";
				}
			}
		}
		if(!userAccountErrorMsg.equals("")){
			tv_msg_userAccount.setText(userAccountErrorMsg);
			refreshErrorMsgTV(tv_msg_userAccount,true);
		}else{
			tv_msg_userAccount.setText("");
			refreshErrorMsgTV(tv_msg_userAccount,false);
		}
		
		//密码
		if(password==null){
			passwordErrorMsg="密码不能为空";
		}else{
			if(password.length()<6){
				passwordErrorMsg="密码长度不能小于6位";
			}else{
				if(!validateUserAccount(password)){
					passwordErrorMsg="密码只能包含数字和字母";
				}
			}
		}
		if(!passwordErrorMsg.equals("")){
			tv_msg_password.setText(passwordErrorMsg);
			refreshErrorMsgTV(tv_msg_password,true);
		}else{
			tv_msg_password.setText("");
			refreshErrorMsgTV(tv_msg_password,false);
		}
		if(passwordErrorMsg.equals("")&&userAccountErrorMsg.equals("")){
			result = true;
		}
		return result;
	}
	
	public String getUserAccount(){
		 String userAccount = et_userAccount.getText().toString();
		 if(userAccount!=null&&!userAccount.trim().equals("")){
			 return userAccount.trim();
		 }
		 return null;
	}
	
	public String getPassword(){
		 String password = et_pwd.getText().toString();
		 if(password!=null&&!password.trim().equals("")){
			 return password.trim();
		 }
		 return null;
	}
	
	
	/**
	 * 校验帐号格式
	 * @param userAccount
	 * @return
	 */
	public boolean validateUserAccount(String userAccount){
		boolean result = false;
		String regx = "[a-zA-Z0-9]*";
		result=userAccount.matches(regx);
		return result;
	}
	
	
	/**
	 * 刷新校验错误信息文本
	 */
	public void refreshErrorMsgTV(final TextView tv,boolean show){
		if(!show){
			if(tv.getVisibility()!=VISIBLE_GONE){
				Animation animation = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
				animation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						tv.setVisibility(VISIBLE_GONE);
					}
				});
				tv.startAnimation(animation);
			}
		}else{
			if(tv.getVisibility()!=VISIBLE_VISIBLE){
				tv.setVisibility(VISIBLE_VISIBLE);
				Animation animation = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
				tv.startAnimation(animation);
			}
		}
	}

}
